var toyApp=angular.module('toyApp');

toyApp.factory('toyService', 
	[
		'$http',
		'$timeout',
		'$rootScope', 
	function($http,$timeout,$rootScope){
	
	var info={},
	reqs={
		queryWishList:'/toy/wish/wishlist',//获取玩具列表
		gettoydetail:'/toy/toyinfo/detail',//获取玩具明细
		createorder:'/toy/order/create',       //根据预约列表生成订单
		queryOrderBackList:'/toy/order/orderlist',
		orderback:'/toy/orderback/create',          //用户回库操作
		toysheleves:'/toy/orderback/shelves', //用户租借物品重新上架
		orderbacklist:'/toy/orderback/backlist', //获得回库列表
		toywish:'/toy/oauth',              //用户产品预约
		querytoylist:'/toy/toyinfo/list',         //获取玩具列表
		creteexpress:'/toy/express/create',     //创建用户订单信息
		queryapplyreturn:'/toy/applyreturn/list'
	};

	//处理Ajax请求流程
	function processHandler(name,callback,data,type){
		if(!reqs.hasOwnProperty(name)){
			return callback({},'接口定义不存在');
		}

		var url=reqs[name],
		args=Array.prototype.splice.call(arguments,0),
		arg_third=args[2],
		arg_forth=args[3],
		params={},
		reqType='GET';
		
		//检查有没有传递data type参数
		//如果第三个参数是object类型
		
		if($.type(arg_third)=='object'){
			params=arg_third;	
		}
		//如果第三个字符串是POST或者GET字符串
		if($.type(arg_third)=='string' && 'POST GET'.indexOf(arg_third.toUpperCase())!=-1){
			reqType=arg_third.toUpperCase();
		}
		//如果第四个字符串是POST或者GET字符串
		if($.type(arg_forth)=='string' && 'POST GET'.indexOf(arg_forth.toUpperCase())!=-1){
			reqType=arg_forth.toUpperCase();
		}
		if(reqType=='GET'){
			$http.get(url,{
				params:params
			}).success(function(res){
				callback(res);
			});
		}else if(reqType=='POST'){
			$http({
				url:url,
				data:params,
				method:'POST',
				headers:{
					'Content-Type':'application/x-www-form-urlencoded;chartset=utf-8'
				}
			}).success(function(res){
				callback(res);
			});
		}

	}

	return processHandler;
}]);
//在两个controller之间通信
toyApp.factory('broadcastBetweenCtrls', ['$rootScope', function($rootScope){
	var cbBox={};
	var on=function(name,cb){
		var cbs=cbBox[name]?cbBox[name]:(cbBox[name]=[]);
		cbs.push(cb);
	};
	var trigger=function(name){
		var params=Array.prototype.slice.call(arguments,1);
		if(!cbBox[name]){
			return false;
		}
		for(var i=0,len=cbBox[name].length;i<len;i++){
			cbBox[name][i].apply({},params);
		}
	};
	var off=function(name){
		if($.type(name)=='string'){
			var cbs=cbBox[name];
			if(cbs && cbs.length){
				cbBox[name]=cbs=[];
			}
		}else if($.type(name)=='array'){
			$.each(name,function(index,item){
				off(item);
			});
		}
	};
}]);
